import React, { useEffect, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { changeFlag } from "../reducers/flagReducer";
import { queryList, delList, addList } from "../reducers/listReducer";
import { userQuery, userDelById, userAdd } from "../service/userService";

export default function User() {
  const [info, setinfo] = useState({
    username: "",
    userage: "",
  });

  let dispatch = useDispatch();
  let list = useSelector((state) => state.listInfo);

  useEffect(() => {
    dispatch(changeFlag(false));
    if (!list.length) {
      userQuery({}).then((res) => {
        //查询数据  放入全局
        dispatch(queryList(res.data));
      });
    }

    return () => {
      dispatch(changeFlag(true));
    };
  }, []);

  return (
    <div>
      <div>
        <div>
          用户名{" "}
          <input
            value={info.username}
            onChange={(e) => {
              setinfo({
                ...info,
                username: e.target.value,
              });
            }}
          />{" "}
        </div>
        <div>
          年龄{" "}
          <input
            value={info.userage}
            onChange={(e) => {
              setinfo({
                ...info,
                userage: e.target.value,
              });
            }}
          />{" "}
        </div>
        <button onClick={()=>{
            userAdd(info).then(res=>{
                dispatch(addList(res.data));
            })
        }}>新增</button>
      </div>
      <div className="tr">
        <div className="td">编号</div>
        <div className="td">用户名</div>
        <div className="td">年龄</div>
        <div className="td">操作</div>
      </div>
      {list.map((item) => {
        return (
          <div className="tr" key={item.id}>
            <div className="td">{item.id}</div>
            <div className="td">{item.username}</div>
            <div className="td">{item.userage}</div>
            <div
              className="td"
              onClick={() => {
                userDelById(item.id).then(() => {
                  //删除接口数据
                  dispatch(delList(item.id)); //删除同步状态
                });
              }}
            >
              删除
            </div>
          </div>
        );
      })}
    </div>
  );
}
